package photorganizer.common.logging;

import java.text.Format;
import java.text.MessageFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;

public class PatternFormatter extends Formatter {

	public static final String DEFAULT_PATTERN = "%level\t%date %class %method - %message\n";

	private static String pattern;

	static {
		LogManager manager = LogManager.getLogManager();
		pattern = manager.getProperty(PatternFormatter.class.getName() + ".pattern");
		if (pattern == null) {
			pattern = DEFAULT_PATTERN;
		}

		pattern = pattern.replaceAll("%class", "{0}");
		pattern = pattern.replaceAll("%date[{]", "{1,date,");
		pattern = pattern.replaceAll("%date", "{1,date,dd-MM-yyyy HH:mm:ss,SSS}");
		pattern = pattern.replaceAll("%level", "{2}");
		pattern = pattern.replaceAll("%logger", "{3}");
		pattern = pattern.replaceAll("%message", "{4}");
		pattern = pattern.replaceAll("%method", "{5}");
		pattern = pattern.replaceAll("%number", "{6}");
		pattern = pattern.replaceAll("%thread", "{7}");
	}

	private final Format format;

	public PatternFormatter() {
		format = new MessageFormat(pattern);
	}

	@Override
	public synchronized String format(LogRecord record) {
		Object[] arguments = new Object[8];
		arguments[0] = record.getSourceClassName();
		arguments[1] = new Date(record.getMillis());
		arguments[2] = record.getLevel();
		arguments[3] = record.getLoggerName();
		arguments[4] = formatMessage(record);
		arguments[5] = record.getSourceMethodName();
		arguments[6] = record.getSequenceNumber();
		arguments[7] = record.getThreadID();

		return format.format(arguments);
	}

}